import axios, {CreateAxiosDefaults} from 'axios';
import router from '@/router/index.ts';
import global from '@/utils/global.ts';
import {delTokenInfo} from '@/utils/token.ts';
import {destroyMessage, errorMessage} from '@/naive/api/index.ts';
import {addAuthorization, getError, getResponse, gotoLogin} from '@/api/request/request.ts';

const request = axios.create(<CreateAxiosDefaults>{
  // 配置基本访问路径
  baseURL: '/api',
  // 配置超时时间
  timeout: 30000,
  // 跨域请求，允许保存cookie
  withCredentials: true,
  // 设置默认请求头
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  },
  // 返回其他状态吗
  validateStatus: (status) => {
    // 默认的
    return status >= 200 && status <= 500;
  }
});

// http request 拦截
request.interceptors.request.use(config => {
  addAuthorization(config);
  return config;
}, error => {
  return Promise.reject(error);
});

// http response 拦截
request.interceptors.response.use((res: any) => {
  const response = getResponse(res);
  // console.log('response = ', response);
  if (response.status !== 200) {
    destroyMessage();
    errorMessage(response.message);
    if (response.status === 401) {
      delTokenInfo();
      let _gotoLogin = gotoLogin(res);
      if (_gotoLogin) {
        router.push(global.loginPage.path);
      }
    }
    return Promise.reject(response);
  }
  return response;
}, err => {
  const error = getError(err);
  // console.log('error = ', error);
  destroyMessage();
  errorMessage(error.message);
  return Promise.reject(error);
});

export default request;
